package threadPool;

import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: 李德才
 * @description:
 * @create: 2020-12-19 19:32
 **/
public class T04_ThreadPool2 implements Runnable {

    private int i;

    public T04_ThreadPool2(int i) {
        this.i = i;
    }

    @Override
    public void run() {
        try {
            System.err.println(Thread.currentThread().getName() + "MyRunnable" + i);
//            手动阻塞
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 4, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(4),
//                new ThreadPoolExecutor.DiscardOldestPolicy()
                new ThreadPoolExecutor.CallerRunsPolicy()
//                new ThreadPoolExecutor.AbortPolicy()
//                new ThreadPoolExecutor.DiscardPolicy()
        );
        /**
         * 为什么是 8 个线程
         * 这里是先使用核心线程 ===> 2 个
         * 核心线程占满的情况下会将线程存入 ** 队列 ** ====> 4 个
         * ** 队列 ** 占满后开始加线程 ===> 最多不能超过 4 个
         *
         */
//        占满线程池
        for (int i = 0; i < 8; i++) {
            threadPoolExecutor.execute(new T04_ThreadPool2(i));
        }
        System.err.println(threadPoolExecutor.getQueue());
        threadPoolExecutor.execute(new T04_ThreadPool2(100));
        System.err.println(threadPoolExecutor.getQueue());
        threadPoolExecutor.shutdown();
    }

    @Override
    public String toString() {
        return "MyRunnable{" +
                "i=" + i +
                '}';
    }
}
